//
//  LevelGageItemView.m
//  XTCloud
//
//  Created by QA on 2018/7/23.
//  Copyright © 2018年 ShangHai HaoLei Software Technology Co., Ltd. All rights reserved.
//

#import "LevelGageItemView.h"
#import "Charts-Swift.h"
#import "NSDictionary+DataFormat.h"
#import "StringAxisValueFormatter.h"
#import "GEDateFromatter.h"
#import "StringValueFormatter.h"
#import "WebServiceCommonRequest.h"

@interface LevelGageItemView ()

@property (nonatomic, strong) BarChartView *chartView;
@property (nonatomic, strong) NSArray *tableArray;

@property (nonatomic, strong) NSMutableArray *buttonArray;
@property (nonatomic, strong) NSMutableArray *indicatorArray;

@property (nonatomic, strong) UILabel *titleSub;

@end

@implementation LevelGageItemView

- (instancetype) initWithData:(NSArray*)data {
    self = [super init];
    if(self){
        [self drawView:data];
    }
    return self;
}

// 绘制相关图表
- (void) drawView:(NSArray*)array {
    self.tableArray = array;
    
    UILabel *title = [[UILabel alloc] initWithFrame:CGRectMake(15, 8, 80, 20)];
    title.text = @"料位计探测";
    title.font=[UIFont systemFontOfSize:13];
    [self addSubview:title];
    
    self.titleSub = [[UILabel alloc] initWithFrame:CGRectMake(89, 8, SuperWidth-100, 20)];
    _titleSub.text = [NSString stringWithFormat:@"数据更新于%@", [GEDateFromatter stringFromDate:[NSDate date]]];
    _titleSub.font=[UIFont systemFontOfSize:11];
    _titleSub.textColor = [UIColor colorWithWhite:0.3 alpha:1];
    [self addSubview:_titleSub];
    
    //绘制图表
    UIView *chartView = [self drawChartView:array];
    [self addSubview:chartView];
    
    //绘制探测按钮
    [self drawProbeButton:array];
}

- (void)drawProbeButton:(NSArray*)valueArray {
    NSInteger barCount = valueArray.count;
    self.buttonArray = [NSMutableArray array];
    self.indicatorArray = [NSMutableArray array];
    
    for(NSInteger i=0;i<barCount;i++){
        NSDictionary *mDictionary = [valueArray objectAtIndex:i];
        NSInteger probeState = [mDictionary objectFormatIntegerForKey:@"探测状态"];
        
        UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
        button.frame = CGRectMake(i*(SuperWidth*0.8/barCount)+SuperWidth*0.2/(barCount+1)*(i+1), 196, SuperWidth*0.8/barCount, 26);
        [button setTitle:@"探测" forState:UIControlStateNormal];
        button.titleLabel.font = [UIFont systemFontOfSize:13];
        [button setTitleColor:[UIColor darkGrayColor] forState:UIControlStateNormal];
        button.layer.cornerRadius = 1; //圆角（圆形）
        button.layer.borderWidth = 0.5;
        button.layer.borderColor = [UIColor colorWithWhite:0.75 alpha:1].CGColor; //要设置的颜色
        [button addTarget:self action:@selector(queryNetWorkProbeData:) forControlEvents:UIControlEventTouchUpInside];
        button.tag = i;
        [self addSubview:button];
        [self.buttonArray addObject:button];
        
        UIActivityIndicatorView *activityIndicator = [[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:(UIActivityIndicatorViewStyleGray)];
        activityIndicator.frame= button.frame;
        activityIndicator.center = button.center;
        activityIndicator.layer.cornerRadius = 1; //圆角（圆形）
        activityIndicator.layer.borderWidth = 0.5;
        activityIndicator.layer.borderColor = [UIColor colorWithWhite:0.75 alpha:1].CGColor; //要设置的颜色
        activityIndicator.hidesWhenStopped = YES;
        [self addSubview:activityIndicator];
        [self.indicatorArray addObject:activityIndicator];
        
        //探测状态按钮处理
        if(probeState >= 1){
            button.hidden = YES;
            activityIndicator.hidden = NO;
            [activityIndicator startAnimating];
            
            //正在探测状态，延迟3秒执行网络查询
            id weakSelf = self;
            dispatch_time_t delayTime = dispatch_time(DISPATCH_TIME_NOW, (int64_t)(3.0 * NSEC_PER_SEC));
            dispatch_after(delayTime, dispatch_get_main_queue(), ^{
                [weakSelf queryNetWorkProbeData:button];
            });
        } else {
            button.hidden = NO;
            activityIndicator.hidden = YES;
        }
    }
}

#pragma mark - 原材供方偏差

- (UIView*)drawChartView:(NSArray*)valueArray
{
    UIView *contentView = [[UIView alloc] initWithFrame:CGRectMake(0, 25, SuperWidth, 180)];
    
    _chartView = [[BarChartView alloc] initWithFrame:CGRectMake(0, 0, SuperWidth, 165)];
//    _chartView.descriptionText = @"";
    _chartView.noDataText = @"暂无数据";
    
    _chartView.chartDescription.enabled = NO;
    _chartView.pinchZoomEnabled = NO;
    _chartView.drawBarShadowEnabled = YES;
    _chartView.drawGridBackgroundEnabled = NO;
    
    ChartLegend *legend = _chartView.legend;
    legend.font = [UIFont fontWithName:@"HelveticaNeue-Light" size:10.f];
    legend.horizontalAlignment = ChartLegendHorizontalAlignmentLeft;
    legend.verticalAlignment = ChartLegendVerticalAlignmentBottom;
    legend.orientation = ChartLegendOrientationHorizontal;
    legend.enabled = NO;
    
    ChartXAxis *xAxis = _chartView.xAxis;
    xAxis.labelFont = [UIFont fontWithName:@"HelveticaNeue-Light" size:10.f];
    xAxis.labelPosition = XAxisLabelPositionBottom;
    xAxis.drawGridLinesEnabled = NO;
    xAxis.drawAxisLineEnabled = NO;
    
    ChartYAxis *leftAxis = _chartView.leftAxis;
    leftAxis.labelFont = [UIFont fontWithName:@"HelveticaNeue-Light" size:10.f];
    leftAxis.spaceTop = 0.25;
    leftAxis.axisMinimum = 0;
    leftAxis.axisMaximum = 100;
    leftAxis.enabled = NO;
    
    ChartYAxis *rightAxis = _chartView.rightAxis;
    rightAxis.labelFont = [UIFont fontWithName:@"HelveticaNeue-Light" size:10.f];
    rightAxis.drawGridLinesEnabled = NO;
    rightAxis.spaceTop = 0.25;
    rightAxis.axisMinimum = 0;
    rightAxis.axisMaximum = 100;
    rightAxis.enabled = NO;
    
    [self generateBar:_chartView data:valueArray];
    [contentView addSubview:_chartView];
    
    return contentView;
}

- (void)generateBar:(BarChartView*)chartView data:(NSArray*)array
{
    NSMutableArray *yVals = [[NSMutableArray alloc] init];
    NSMutableArray *xVals = [NSMutableArray array];
    NSMutableArray *barVals = [NSMutableArray array];
    
    for (int i = 0; i < array.count; i++) {
        NSDictionary *mDictionary = [array objectAtIndex:i];
        CGFloat skgd = [mDictionary objectFormatFloatForKey:@"上空高度"];
        CGFloat lgd = [mDictionary objectFormatFloatForKey:@"料高度"];
        NSString *clmc = [mDictionary objectFormatStringForKey:@"材料名称"];
        
        CGFloat bfb = lgd / (skgd + lgd)*100;
        [yVals addObject:[[BarChartDataEntry alloc] initWithX:i y:bfb]];
        [xVals addObject:clmc];
        [barVals addObject:[NSString stringWithFormat:@"上空%0.1f米",skgd]];
    }
    
    //设置底部显示文字
    chartView.xAxis.granularity = 1.0; // only intervals
    chartView.xAxis.valueFormatter = [[StringAxisValueFormatter alloc] initWithData:xVals];
    chartView.xAxis.labelCount = xVals.count;
    
    BarChartDataSet *set1 = [[BarChartDataSet alloc] initWithValues:yVals label:@"材料"];
    [set1 setColors:ChartColorTemplates.material];
    
    NSMutableArray *dataSets = [[NSMutableArray alloc] init];
    [dataSets addObject:set1];
    
    BarChartData *data = [[BarChartData alloc] initWithDataSets:dataSets];
    [data setValueFont:[UIFont fontWithName:@"HelveticaNeue-Light" size:10.f]];
    [data setValueTextColor:[UIColor darkGrayColor]];
    [data setValueFormatter:[[StringValueFormatter alloc] initWithData:barVals]];
    
    data.barWidth = 0.8f;
    chartView.data = data;
    
    //变更更新时间
    _titleSub.text = [NSString stringWithFormat:@"数据更新于%@", [GEDateFromatter stringFromDate:[NSDate date]]];
}

#pragma mark 下探测试
- (void)queryNetWorkProbeData:(UIButton*)button
{
    NSInteger tagIndex = button.tag;
    NSDictionary *mDictionary = [self.tableArray objectAtIndex:tagIndex];
    NSString *clID = [mDictionary objectFormatStringForKey:@"材料ID"];
    NSString *scxID = [mDictionary objectFormatStringForKey:@"生产线ID"];
    
    UIButton *tcButton = [self.buttonArray objectAtIndex:tagIndex];
    UIActivityIndicatorView *activityIndicator = [self.indicatorArray objectAtIndex:tagIndex];
    tcButton.hidden = YES;
    activityIndicator.hidden = NO;
    [activityIndicator startAnimating];
    
    WebServiceCommonRequest *content = [[WebServiceCommonRequest alloc] init];
    [content setInterfaceType:InterfaceTypeGroup];
    [content setModuleType:@"ZNYJ-LWJTC-TC"];
    [content setResultBackType:ResultBackTypeCommonUnordered];
    [content addParameterKey:@"材料ID" value:clID];
    [content addParameterKey:@"生产线ID" value:scxID];
    
    [content startAsyncConnectCompleted:^(ServiceResultModel *result, NSDictionary *userInfo) {
        //添加数据，刷新页面
        NSArray *firstArray = nil;
        if(result.resultArray && result.resultArray.count>=1){
            firstArray = [result.resultArray firstObject];
        }

        //显示数据处理
        if(firstArray && firstArray.count>0){
            [self generateBar:_chartView data:firstArray];
            
            NSDictionary *mDictionary = [firstArray objectAtIndex:tagIndex];
            NSInteger tcState = [mDictionary objectFormatIntegerForKey:@"探测状态"];
            if(tcState == 1){
                //正在探测状态，延迟3秒执行
                id weakSelf = self;
                dispatch_time_t delayTime = dispatch_time(DISPATCH_TIME_NOW, (int64_t)(3.0 * NSEC_PER_SEC));
                dispatch_after(delayTime, dispatch_get_main_queue(), ^{
                    [weakSelf queryNetWorkProbeData:button];
                });
            } else {
                // 探测完成，还原按钮
                tcButton.hidden = NO;
                activityIndicator.hidden = YES;
                [activityIndicator stopAnimating];
            }
        }
        
    } failed:^(NSError *error, NSDictionary *userInfo) {
        NSLog(@"=====%@",error);
        tcButton.hidden = NO;
        activityIndicator.hidden = YES;
        [activityIndicator stopAnimating];
        
    } abnormal:^(NSError *error, NSDictionary *userInfo) {
        NSLog(@"=====%@",error);
        tcButton.hidden = NO;
        activityIndicator.hidden = YES;
        [activityIndicator stopAnimating];
    }];
    
}


@end
